import { checkPhone, goldConfigOpp, isNullPm, loctionTime, ruleLivingExample } from '@/utils/baseMethods';
import { reactive } from 'vue';
import { formDataDom } from './basics/dom';
import { loginIoFo } from '@/api/url/login';
import { useCounterStore } from '@/pinia/pinia';
import router from '@/router';
import { showNotify } from '@nutui/nutui';

export default function importFunction() {
  const base = reactive<any>({
    formData: null,
    ruleForm: null,
  });
  const init = () => {
    // console.log(import.meta.env.VITE_APP_API_BASE_URL);
    base.formData = formDataDom();
    phoneRules();
  };

  /**
   * @example submitUp 表单提交
   */
  const submitUp = () => {
    base.ruleForm.validate().then(({ valid, errors }: any) => {
      /**
       * 校验成功
       */
      if (valid) {
        loginIoFo(base.formData).then((res: any) => {
          if (res.success) {
            const userInFo = useCounterStore();
            const tokenFon = {
              token: '-dt-' + loctionTime() + '-sd-',
            };
            userInFo.setGm(tokenFon);
            router.push('/home');
          } else {
            showNotify.warn(res.errorMsg);
          }
        });
      }
    });
  };

  /**
   * @exports releuList 规则列表
   * @returns
   */
  const releuList = () => {
    return {
      userName: phoneRules(),
      passWord: passWordRules(),
    };
  };

  /**
   * @exports phoneRules 手机号码的规则
   */
  const phoneRules = () => {
    /**
     * releuPhoneDomA 校验数据手机号码不能为空
     */
    const releuPhoneDom = ruleLivingExample({
      title: '手机号码不能为空',
      method: (val: any): any => {
        if (isNullPm(val)) return Promise.reject('手机号码不能为空');
        else if (!checkPhone(val) && !goldConfigOpp('AdministratorAccount', val)) return Promise.reject('手机号码格式错误');
        else return true;
      },
    });
    return [releuPhoneDom.RuleBody];
  };

  /**
   * @exports passWordRules 密码的校验规则
   */
  const passWordRules = () => {
    const releuDom = ruleLivingExample({
      title: '密码不能为空',
      method: (val: any): any => {
        if (isNullPm(val)) return Promise.reject('密码不能为空');
        else {
          return Promise.resolve();
        }
      },
    });
    return [releuDom.RuleBody];
  };
  return {
    base,
    init,
    phoneRules,
    passWordRules,
    releuList,
    submitUp,
  };
}

function userPPm() {
  throw new Error('Function not implemented.');
}
